import numpy
import threading
import wx
from collections import deque
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import zpr

TASK = 0
ARG1 = 1
ARG2 = 1
task_list = deque([])
task_list_cond = threading.Condition()
out_list = dict()
out_list_lock = threading.Lock()

cv = threading.Condition()

class Worker(threading.Thread):
    
    def putTask(self, task, arg1, arg2):
        task_list_cond.aquire()
        task_list.append([task, arg1, arg2])
        task_list_cond.notifyAll()
        task_list_cond.release()
    
    def run(self):
        task_list_cond.aquire()
        while task_list.len() == 0:
            task_list_cond.wait()  
        todo = task_list.popleft()
        task_list_cond.release()
        result = todo[TASK](todo[ARG1], todo[ARG2])
        hash_code= hash(task) + hash(arg1) + hash(arg2)
        out_list_lock.aquire()
        out_list[hash_code] = result
        out_list_lock.release()
        
class Renderer(threading.Thread):
    
    def __init__(self, canvas):
        threading.Thread.__init__(self)
        self.canvas = canvas
    
    def run(self):
        print "thread"
        self.light = numpy.array([0.0, 11.0, 6.0, 1.0], dtype = numpy.float32)
        zpr.init(self.canvas)
        glClearColor(0.5, 0.2, 1.0, 1.0)
        
        glEnable(GL_DEPTH_TEST)
        glShadeModel(GL_SMOOTH)
        
        glEnable(GL_LIGHTING)
        glEnable(GL_LIGHT0)
        glEnable(GL_NORMALIZE)
        
        glEnable(GL_CULL_FACE)
        glCullFace(GL_BACK)
        
        glEnable(GL_LINE_SMOOTH)
        glEnable(GL_POLYGON_SMOOTH)
        while True:
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
            
            size = self.canvas.GetSize()
            glViewport(0, 0, size.width, size.height)
            
            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()
            gluPerspective(60.0, float(size.width) / float(size.height), 0.01, 100.0)
            
            glMatrixMode(GL_MODELVIEW)
            glLoadIdentity()
    
            glMultMatrixf(zpr.zprGetCameraMatrix())
            
            #light fixed -> does not move with the camera
            glLightfv(GL_LIGHT0, GL_POSITION, self.light)
            
            glPushMatrix()
            color = [1.0,0.0,0.0,1.0]
            glMaterialfv(GL_FRONT,GL_DIFFUSE,color)
            glTranslate(0, 0, -10)
            glutSolidSphere(2,20,20)
            glPopMatrix()
            
